package com.chinawlx.wlxteacher.ui.adapter;

import android.content.Context;
import android.content.Intent;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXClazzHomeWorkBean;
import com.chinawlx.wlxteacher.network.bean.WLXGetCodeBean;
import com.chinawlx.wlxteacher.ui.activity.WLXParentRplyctivity;
import com.chinawlx.wlxteacher.ui.activity.WLXPlayVideoActivity;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.widget.nine_grid.WLXGridLayout;
import com.chinawlx.wlxteacher.wlx_homework;
import com.chinawlx.wlxteacher.wlx_student;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscriber;


/**
 * 作业点评界面适配器
 */
public class WLXHomeworkCommentAdapter extends BaseAdapter {

    private final int NO_REPLY = 1;
    private final int HISTORY_REPLY = 2;
    private final int TEXT = 3;

    private Context mContext;
    private ArrayList<wlx_homework> mNoCommitData = new ArrayList<>();//未点评
    private ArrayList<wlx_homework> mHistoryData = new ArrayList<>();//历史数据

    public WLXHomeworkCommentAdapter(Context context) {
        this.mContext = context;
    }

    /**
     * 未点评数据
     *
     * @param noCommitData
     */
    public void setNoCommitData(List<wlx_homework> noCommitData) {
        mNoCommitData.clear();
        mNoCommitData.addAll(noCommitData);
    }

    /**
     * 历史数据
     *
     * @param historyData
     */
    public void setHistoryData(List<wlx_homework> historyData) {
        mHistoryData.clear();
        mHistoryData.addAll(historyData);
    }

    /**
     * 未点评数据
     *
     * @param noCommitData
     */
    public void addNoCommitData(List<wlx_homework> noCommitData) {
        mNoCommitData.addAll(noCommitData);
    }

    /**
     * 历史数据
     *
     * @param historyData
     */
    public void addHistoryData(List<wlx_homework> historyData) {
        mHistoryData.addAll(historyData);
    }

    @Override
    public int getViewTypeCount() {
        return 1 + mHistoryData.size() + mNoCommitData.size();//显示几种数据就要写几种类型,不然会报数据越界异常
    }

    @Override
    public int getItemViewType(int position) {
        //[0,3) 3 [4,2+3+1)一起3+2+1个item
        if (position == mNoCommitData.size()) {
            return TEXT;
        }
        if (position >= 0 && position < mNoCommitData.size()) {
            return NO_REPLY;
        }
        if (position >= mNoCommitData.size() + 1 && position < mNoCommitData.size() + 1 +
                mHistoryData.size()) {
            return HISTORY_REPLY;
        }
        return -1;
    }

    @Override
    public int getCount() {
        int i = mNoCommitData.size() + 1 + mHistoryData.size();
        return i == 1 ? 0 : i;
    }

    @Override
    public Object getItem(int position) {
        int type = getItemViewType(position);
        if (type == NO_REPLY) return mNoCommitData.get(position);
        if (type == HISTORY_REPLY) return mHistoryData.get(position - 1 - mNoCommitData.size());
        return -1;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        int type = getItemViewType(position);
        switch (type) {
            case TEXT:
                TextView text = new TextView(mContext);
                ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams
                        .MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                text.setLayoutParams(params);
                text.setText("以下为点评历史记录");
                text.setGravity(Gravity.CENTER_HORIZONTAL);
                convertView = text;
                break;
            case NO_REPLY:
                convertView = initHolderView(mNoCommitData.get(position), convertView);
                break;
            case HISTORY_REPLY:
                convertView = initHolderView(mHistoryData.get(position - mNoCommitData.size() - 1),
                        convertView);//0 1 2 3 4
                break;
        }
        return convertView;
    }

    //初始化视图
    private View initHolderView(final wlx_homework wlx_homework, View convertView) {
        ViewHolder holder;
        if (convertView == null || convertView instanceof TextView) {
            convertView = LayoutInflater.from(mContext).inflate(R.layout
                    .item_homework_comment_view, null);
            holder = new ViewHolder();
            holder.mIvVideoCover = (ImageView) convertView.findViewById(R.id.iv_video_cover);
            holder.mTvCommentDianping = (TextView) convertView.findViewById(R.id
                    .tv_comment_dianping);
            holder.mTvVideoTime = (TextView) convertView.findViewById(R.id.tv_video_time);
            holder.mRlVideoContainer = (RelativeLayout) convertView.findViewById(R.id
                    .rl_video_container);
            holder.mLayoutNineGrid = (WLXGridLayout) convertView.findViewById(R.id
                    .layout_nine_grid);
            holder.mIvVideoImg = (ImageView) convertView.findViewById(R.id.iv_video_img);
            holder.mReport = (TextView) convertView.findViewById(R.id.report);
            holder.mTvCommentDone = (TextView) convertView.findViewById(R.id.tv_comment_done);
            holder.mTvContent = (TextView) convertView.findViewById(R.id.tv_content);
            holder.mUserPhoto = (CircleImageView) convertView.findViewById(R.id.user_photo);
            holder.mTvUserName = (TextView) convertView.findViewById(R.id.tv_user_name);
            holder.mTvTime = (TextView) convertView.findViewById(R.id.tv_time);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        //初始化数据
        //通过student_id查找student表,拿到名称和头像的URL
        final wlx_student student = WLXGreenDaoUtil.getStudentDao().load(wlx_homework
                .getStudent_id() + "");
        if (student != null) {
            holder.mTvUserName.setText(student.getRealname());
            Glide.with(mContext).load(student.getAvatar_url()).placeholder(R.drawable.place_holder).into(holder.mUserPhoto);
        } else {
            holder.mTvUserName.setText(wlx_homework.getStudent_id() + "");
        }

        //获取时间
        long current_time = System.currentTimeMillis() / 1000L;
        long creatData = wlx_homework.getCreation_date();
        //获取现在时间和创始时间的差值
        final String time = WLXDateUtil.getDistanceTime(creatData, current_time);
        holder.mTvTime.setText(time);

        //实际内容
        holder.mTvContent.setText(wlx_homework.getContent());

        //点评的点击事件 1表示已经点评 0 表示未点评
        if (wlx_homework.getIs_teacher_comment() != 1) {
            holder.mTvCommentDianping.setVisibility(View.VISIBLE);
            holder.mTvCommentDone.setVisibility(View.GONE);
            holder.mTvCommentDianping.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, WLXParentRplyctivity.class);
                    intent.putExtra("homework_id", wlx_homework.getHomework_id());
                    intent.putExtra("student_id", wlx_homework.getStudent_id()
                            + "");
                    intent.putExtra("homework_content_code", wlx_homework
                            .getHomework_content_code());
                    intent.putExtra("time", time);
                    intent.putExtra("extend_info", wlx_homework.getExtend_info());
                    intent.putExtra("content", wlx_homework.getContent());
                    intent.putExtra("userIcon", student == null ? "" : student.getAvatar_url());
                    mContext.startActivity(intent);
                }
            });
        } else {
            holder.mTvCommentDianping.setVisibility(View.INVISIBLE);
            holder.mTvCommentDone.setVisibility(View.VISIBLE);
            holder.mTvCommentDone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(mContext, WLXParentRplyctivity.class);
                    intent.putExtra("homework_id", wlx_homework.getHomework_id());
                    intent.putExtra("student_id", wlx_homework.getStudent_id()
                            + "");
                    intent.putExtra("homework_content_code", wlx_homework
                            .getHomework_content_code());
                    intent.putExtra("time", time);
                    intent.putExtra("extend_info", wlx_homework.getExtend_info());
                    intent.putExtra("content", wlx_homework.getContent());
                    intent.putExtra("userIcon", student == null ? "" : student.getAvatar_url());
                    mContext.startActivity(intent);
                }
            });
        }

        holder.mReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toReport(wlx_homework.getHomework_id());
            }
        });

        //处理图片或视频
        String extend_info = wlx_homework.getExtend_info();
        final WLXClazzHomeWorkBean.DataBean.HomeworkListBean.ExtendBean extendBean = new Gson()
                .fromJson(extend_info, new TypeToken<WLXClazzHomeWorkBean
                        .DataBean.HomeworkListBean.ExtendBean>() {
                }.getType());

        switch (wlx_homework.getHomework_content_code()) {
            case "image":
                holder.mRlVideoContainer.setVisibility(View.GONE);
                holder.mLayoutNineGrid.setVisibility(View.VISIBLE);
                holder.mLayoutNineGrid.setMaxImageNumTo3();
                holder.mLayoutNineGrid.setUrlList(extendBean.getResource_url());
                break;
            case "video":
                holder.mRlVideoContainer.setVisibility(View.VISIBLE);
                holder.mLayoutNineGrid.setVisibility(View.GONE);

                if (extendBean.getResource_url().size() != 0) {
                    String ss = extendBean.getResource_url().get(0);
                    String url = ss.substring(0, ss.length() - 3) + "png";
                    Glide.with(mContext).load(url).placeholder(R.drawable.place_holder).into(holder.mIvVideoImg);
                    holder.mTvVideoTime.setText(extendBean.getDuration() + "″");
                    holder.mIvVideoCover.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            try {
                                String videoUrl = extendBean
                                        .getResource_url().get(0);
                                Intent intent = new Intent(mContext,
                                        WLXPlayVideoActivity.class);
                                intent.putExtra(WLXPlayVideoActivity.VIDEO_URL, videoUrl);
                                mContext.startActivity(intent);
                            } catch (Exception e) {
                                e.printStackTrace();
                                Toast.makeText(mContext, "该视频无法播放", Toast.LENGTH_SHORT)
                                        .show();
                            }
                        }
                    });
                }
                break;
        }
        return convertView;
    }

    static class ViewHolder {
        CircleImageView mUserPhoto;
        TextView mTvContent;
        TextView mTvUserName;
        TextView mTvTime;
        TextView mTvCommentDianping;
        TextView mTvCommentDone;
        ImageView mIvVideoImg;//视频图片展示
        ImageView mIvVideoCover;//视频覆盖层
        WLXGridLayout mLayoutNineGrid;//图片
        TextView mReport;//举报
        TextView mTvVideoTime;//时间
        RelativeLayout mRlVideoContainer;//视频容器
    }

    /**
     * 举报不良信息
     */
    private void toReport(String resource_id) {
        WLXHttpRxHelper.getInstance().report(resource_id, "schedule", "", new
                Subscriber<WLXGetCodeBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        WLXCustomToast.show("举报失败,请检查网络");
                    }

                    @Override
                    public void onNext(WLXGetCodeBean reportBean) {
                        if (reportBean.getCode() == 0) {
                            WLXCustomToast.show("举报成功");
                        } else {
                            WLXCustomToast.show("重复举报");
                        }
                    }
                });
    }

}


